# coding: utf-8

from flask import Blueprint, render_template, redirect, url_for, flash
from flask_login import login_user, logout_user, login_required, current_user
from flask_principal import Permission, RoleNeed
from flask_login import LoginManager
from user.forms import UserAddForm, UserEditForm
from db.models import db, User, SysUserRole, SysRole
from permission_control import permission_required
from const import PERMISSION, BorrowCardApplyStatus
from config import app

user_blueprint = Blueprint('user_manage', __name__)


@user_blueprint.route('/user_manage/list', methods=['GET'])
@login_required
@permission_required(PERMISSION.PERM_USER_VIEW.KEY)
def user_list():
    query = db.session.query(
            SysUserRole, User
        ).outerjoin(
            User, SysUserRole.user_id==User.id
        ).where(
            SysUserRole.role_key == 'ROLE_BOOK_ADMIN',
            User.is_delete == 0
        ).order_by(
            User.id.desc()
        )
    users = query.all()
    return render_template('user_manage/users.html', users=users, username=current_user.username)


@user_blueprint.route('/user_manage/add', methods=['GET', 'POST'])
@login_required
@permission_required(PERMISSION.PERM_USER_ADD.KEY)
def user_add():
    form = UserAddForm()
    if form.validate_on_submit():
        existing_user = User.query.filter_by(
            username=form.username.data).first()
        if existing_user is None:
            user = User(username=form.username.data)
            user.password = form.password.data
            user.age = form.age.data
            user.birthday = form.birthday.data
            user.is_active = bool(form.is_active.data)
            db.session.add(user)
            # 创建普通用户角色
            common_role = SysRole.query.filter_by(role_key='ROLE_BOOK_ADMIN').first()
            common_user_role = SysUserRole(
                user_id=user.id, 
                username=user.username, 
                role_id=common_role.id, 
                role_key=common_role.role_key)
            db.session.add(common_user_role)
            db.session.commit()
            flash('添加成功！', 'success')
            return redirect(url_for('user_manage.user_list'))
        else:
            flash(f'用户{form.username.data}已被使用，请尝试添加其他用户。', 'danger')
        
    else:
        flash(f'添加失败！{form.errors}', 'danger')
    return render_template('user_manage/user_add.html', form=form)


@user_blueprint.route('/user_manage/edit/<int:user_id>', methods=['GET', 'POST'])
@login_required
@permission_required(PERMISSION.PERM_USER_EDIT.KEY)
def user_edit(user_id):
    user = User.query.filter_by(id=user_id).first()
    if not user:
        flash('没有找到该用户。', 'danger')
        return redirect(url_for('user.user_list'))
    form = UserEditForm(obj=user)
    if form.validate_on_submit():
        form.populate_obj(user)
        db.session.commit()
        flash('用户信息已更新！', 'success')
        return redirect(url_for('user_manage.user_list'))
    return render_template('user_manage/user_edit.html', user=user, form=form)


@user_blueprint.route('/user_manage/is_active/<int:user_id>/<int:is_active>', methods=['GET', 'POST'])
@login_required
@permission_required(PERMISSION.PERM_USER_DELETE.KEY)
def user_active(user_id, is_active):
    if is_active not in [0, 1]:
        flash('无效的操作。', 'danger')
        return redirect(url_for('user_manage.user_list'))
    user = User.query.filter_by(id=user_id).first()
    user.is_active = is_active
    db.session.commit()
    if is_active == 1:
        flash('用户信息已激活！', 'success')
    else:
        flash('用户信息已禁用！', 'success')
    return redirect(url_for('user_manage.user_list'))


@user_blueprint.route('/user_manage/delete/<int:user_id>', methods=['GET', 'POST'])
@login_required
@permission_required(PERMISSION.PERM_USER_DELETE.KEY)
def user_delete(user_id):
    user = User.query.filter_by(id=user_id).first()
    user.is_delete = 1
    db.session.commit()
    flash('用户信息已删除！', 'success')
    return redirect(url_for('user_manage.user_list'))
